package com.yange.accountbook.popup

import android.content.Context
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lxj.xpopup.core.BottomPopupView
import com.yange.accountbook.R
import com.yange.accountbook.entity.AccountEntity
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.ui.adapter.AccountListAdapter
import com.yange.accountbook.utils.showToast

class AccountListBottomPop (context: Context): BottomPopupView(context){

    lateinit var recyclerView : RecyclerView
    lateinit var myAdapter: AccountListAdapter
    lateinit var itemClickListener:OnItemClickListener
    var bookId = 0

    override fun getImplLayoutId() = R.layout.pop_bottom_list_pop

    constructor(context: Context,bookId:Int, itemClickListener: OnItemClickListener) : this(
        context
    ) {
        this.bookId = bookId
        this.itemClickListener = itemClickListener
    }

    override fun onCreate() {
        super.onCreate()
        recyclerView = findViewById(R.id.data_list)
        val title = findViewById<TextView>(R.id.tar_add_title)
        title.text = "请选择账户"
        //和首页同一个适配器
        myAdapter = AccountListAdapter()
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = myAdapter
        getAccountList()
        myAdapter.setOnItemClickListener { adapter, view, position ->
            var item = adapter.getItem(position) as AccountEntity
            itemClickListener.itemClick(item)
            dismiss()
        }
    }
    /**
     * 账户列表
     */
    private fun getAccountList() {
        RetrofitClient.getInstance().invokePostBody(
            context, Api.ACCOUNT_LIST, mapOf(
                "bookId" to bookId
            )
        )
            .subscribe(object : RecObserver<BaseResponse<List<AccountEntity>>>(context, false, false) {
                override fun onSuccess(t: BaseResponse<List<AccountEntity>>?) {
                    myAdapter.setNewInstance(t?.data as MutableList<AccountEntity>?)
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

    interface OnItemClickListener{
        fun itemClick(item: AccountEntity)
    }
}